package top.kaoshanji.p1ch05a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 代码清单-p1ch05a-148页a：管理响应缓冲
 * URL访问地址：/buffering
 * @author kaoshanji
 * ^_^
 * create time 2025/4/4 14:17
 */
public class Buffering extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setBufferSize(8 * 1024); // 8K 缓存
        resp.setContentType(ContentType.TEXT_HTML.toString());

        PrintWriter out = resp.getWriter();
        int size = resp.getBufferSize(); // 返回 8096 或更大

        // 在日志中记录默认大小
        log("The default buffer size is " + size);

        out.println("The client won't see this");
        resp.reset();

        out.println("Nor will the client see this!");
        resp.reset();

        out.println("And this won't be seen if sendError() is called");
        if (req.getParameter("important_parameter") == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "important_parameter needed");
        }

    }

}
